package com.leetcode;

/**
 * 79. 单词搜索
 *
 * @author fy
 * @date 2022/4/1 21:56
 */
public class Solution79 {

    int[][] d = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    boolean[][] visited;
    int m;
    int n;

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || word == null || word.length() == 0) {
            return false;
        }
        m = board.length;
        n = board[0].length;
        visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (searchChar(board, word, 0, i, j)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean searchChar(char[][] board, String word, int index, int x, int y) {
        if (board[x][y] != word.charAt(index)) {
            return false;
        }
        if (index == word.length() - 1 && board[x][y] == word.charAt(index)) {
            return true;
        }
        for (int i = 0; i < d.length; i++) {
            int[] direct = d[i];
            int newX = x + direct[0];
            int newY = y + direct[1];
            if (this.inArea(newX, newY) && !visited[newX][newY]) {
                visited[x][y] = true;
                if (searchChar(board, word, index + 1, newX, newY)) {
                    return true;
                }
                visited[x][y] = false;
            }
        }
        return false;
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < m && y >= 0 && y < n;
    }

    public static void main(String[] args) {
        char[][] board = new char[][]{{'a'}};
        String word = "a";

        boolean exist = new Solution79().exist(board, word);
        System.out.println(exist);
    }
}
